package com.kehutong.flow.service;

import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;
import com.kehutong.flow.entity.FlowOffer;
import com.kehutong.flow.entity.FlowRole;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;

import java.util.*;

@WebService("/flow/service/role")
public class FlowRoleService{

	@Inject
	private JdbcSession jdbcSession;

	@Inject
	private DoveClient doveClient;

	@ReqMapping("/list")
	public  Page<FlowRole> list(JSONObject jsonObject) {
		return jdbcSession.findPage(FlowRole.class)
				.eq(jsonObject, "id", "companyNo")
				.like(jsonObject, "name")
				.eq("deleted", false)
				.order("createTime", "desc")
				.page(jsonObject)
				.exe();
	}

	@ReqMapping("/get")
	public Object get(String id) {
		final FlowRole role = Pool.get(FlowRole.class, id);
		if (Objects.nonNull(role) && role.isDeleted()) {
			return Result.success();
		}

		return role;
	}

	@Bean(newInstance = true, copy = true)
	@ReqMapping("/save")
	public Object save(FlowRole item) {
		FlowRole flowRole = jdbcSession.findOne(FlowRole.class)
				.eq("name", item.getName())
				.eq("deleted", false).exe();

		if (Objects.nonNull(flowRole)) {
			return Result.error(0, "该岗位名称已存在！");
		}

		jdbcSession.insert(item);
		return Result.success();
	}

	@Bean(copy=true)
	@ReqMapping("/update")
	public Object update(FlowRole item) {
		FlowRole temp = Pool.get(FlowRole.class, item.getId());
		if (Objects.isNull(temp)) {
			return Result.error(-1, "该岗位名称不存在！");
		}

		if (!item.getName().equals(temp.getName())){
			List<FlowRole> exe = jdbcSession.findArray(FlowRole.class)
					.eq("name", item.getName())
					.eq("deleted", false).exe();
			if (exe.size() != 0) {
				return Result.error(-1, "该岗位名称已存在！");
			}
		}

		jdbcSession.updateById(item);

		List<FlowOffer> flowOffers = jdbcSession.findArray(FlowOffer.class)
				.eq("roleNo", item.getId())
				.eq("deleted", false).exe();

		if (flowOffers.size() > 0) {
			flowOffers.forEach(flowOffer -> flowOffer.setRoleName(item.getName()));
			jdbcSession.updateById(flowOffers);
		}

		return Result.success();
	}

	@ReqMapping("/delete")
	public Object delete(String id) {
		final FlowRole role = Pool.get(FlowRole.class, id);

		if (Objects.nonNull(role)) {
			List<FlowOffer> flowOffers = jdbcSession.findArray(FlowOffer.class)
					.eq("roleNo", role.getId()).eq("deleted", false).exe();
			if (Objects.nonEmpty(flowOffers)) {
				return Result.error(-1, "请先删除该角色下的所有用户！");
			}

			role.setDeleted(true);
			jdbcSession.updateById(role);
		}

		return Result.success();
	}


	/**
	 * 返回有权限员工
	 *
	 * @param companyNo
	 * @return
	 */
	@ReqMapping("/get/employee/ByCompanyNo")
	public JSONArray getEmployee(Token token) throws Exception {
		List<FlowOffer> offerList;
		offerList = jdbcSession.findArray(FlowOffer.class)
				.eq("companyNo", token.getCompanyNo())
				.eq("deleted", false)
				.exe();

		return getEmployees(offerList, token.getCompanyNo());
	}

	/**
	 * 通过companyNo和roleNo获取员工
	 *
	 * @param companyNo
	 * @param roleNo
	 * @return
	 */
	@ReqMapping("/get/employee/ByRoleNo")
	public JSONArray getEmployee(Token token, String roleNo) throws Exception {
		List<FlowOffer> offerList;
		offerList = jdbcSession.findArray(FlowOffer.class)
				.eq("companyNo", token.getCompanyNo())
				.eq("roleNo", roleNo)
				.eq("deleted", false)
				.exe();

		return getEmployees(offerList, token.getCompanyNo());
	}

	/**
	 * 通过roleNos和companyNo获取员工
	 *
	 * @param companyNo
	 * @param roleNos
	 * @return
	 */
	@ReqMapping("/get/employee/ByRoleNos")
	public JSONArray getEmployee(Token token, List<String> roleNos) throws Exception {
		if (Objects.isEmpty(roleNos)) {
			return new JSONArray();
		}

		List<FlowOffer> offerList;
		offerList = jdbcSession.findArray(FlowOffer.class)
				.eq("companyNo", token.getCompanyNo())
				.in("roleNo", roleNos)
				.eq("deleted", false)
				.exe();

		return getEmployees(offerList, token.getCompanyNo());
	}

	/**
	 * 通过小区编号获取子集的所有员工
	 *
	 * @param companyNo
	 * @param communityNo
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	@ReqMapping("/get/employee/ByDepartmentChildren")
	public JSONArray getEmployeeByDepartmentChildren(Token token, String communityNo, String roleId) throws Exception {
		if (Objects.isEmpty(roleId)) {
			return new JSONArray();
		}

		List<String> departmentList = new ArrayList<>();
		JSONObject object = doveClient.post("/basic/department/service/list", (http) -> {
			http.addHeader("companyNo", token.getCompanyNo());
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("parent_ids", Arrays.asList(communityNo));
			http.setBody(jsonObject.toString());
		});
		if (object.getInteger("code") == 200) {
			JSONArray departments = object.getJSONArray("data");
			if (departments != null && departments.size() != 0) {
				List<String> departmentIds = new ArrayList<>();
				departments.forEach(obj -> {
					JSONObject department = (JSONObject) obj;
					departmentIds.add(department.getString("id"));
				});

				departmentList.addAll(departmentIds);
			}
		}
		departmentList.add(communityNo);

		if (Objects.isEmpty(departmentList)) {
			return new JSONArray();
		}

		List<FlowOffer> offerList = jdbcSession.findArray(FlowOffer.class)
				.in("communityNo", departmentList)
				.in("roleNo",  roleId)
				.eq("deleted", false)
				.exe();

		return getEmployees(offerList, token.getCompanyNo());
	}

	private JSONArray getEmployees(List<FlowOffer> offerList, String companyNo) throws Exception {
    	if (Objects.isEmpty(offerList)) {
    		return new JSONArray();
    	}
    	
    	Set<String> employeeIds = getEmployeeIds(offerList);
    	if (Objects.isEmpty(employeeIds)) {
			return new JSONArray();
    	}

		JSONObject object = doveClient.post("/basic/employee/service/list", (http) -> {
			http.addHeader("companyNo", companyNo);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", new ArrayList<>(employeeIds));
			http.setBody(jsonObject.toString());
		});
		if (object.getInteger("code") == 200) {
			return object.getJSONArray("data");
		} else {
			return new JSONArray();
		}
    }
    
    private Set<String> getEmployeeIds(List<FlowOffer> offerList) {
    	if (Objects.isEmpty(offerList)) {
    		return Collections.emptySet();
    	}
    	
    	Set<String> employeeIds = new HashSet<>();
    	offerList.forEach(offer->employeeIds.add(offer.getEmployeeNo()));
    	
    	return employeeIds;
    }
    
    
}
